package com.xyrl.project.app.core.handler;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.xyrl.common.base.exception.LimitAccessException;
import com.xyrl.common.base.exception.OtherLoginException;
import com.xyrl.common.base.exception.TokenTimeOutException;
import com.xyrl.common.base.exception.XyrlException;
import com.xyrl.project.common.base.vo.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.List;
import java.util.Set;

@Slf4j
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ResponseData handleException(Exception e) {
        log.error("系统内部异常，异常信息：", e);
        return ResponseData.error("系统内部异常");
    }

    @ExceptionHandler(value = XyrlException.class)
    public ResponseData handleParamsInvalidException(XyrlException e) {
        log.warn("系统错误：{}", e.getMessage());
        return ResponseData.error(e.getMessage());
    }

    @ExceptionHandler(value = OtherLoginException.class)
    public ResponseData otherLoginException(OtherLoginException e) {
        log.warn("系统错误：{}", e.getMessage());
        return ResponseData.otherLogin(e.getMessage());
    }
    @ExceptionHandler(value = TokenTimeOutException.class)
    public ResponseData otherTokenTimeOutException(OtherLoginException e) {
        log.warn("系统错误：{}", e.getMessage());
        return ResponseData.error(e.getMessage());
    }


    /***
     * 全局参数异常
     * @author 徐恩源
     * @date 2019-12-31 16:59:00
     * @param e
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseData handlerIllegalArgumentException(IllegalArgumentException e) {
        log.warn("IllegalArgumentException异常：" + e.getMessage());
        return ResponseData.error(e.getMessage());
    }

    /**
     * 方法参数类型不匹配异常
     * @author 徐恩源
     * @date 2019-12-30 10:07:13
     * @param e
     */
    @ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
    public ResponseData handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        log.error("参数类型错误：", e);
        return ResponseData.error("参数【" + e.getParameter().getParameterName() + "】类型错误");
    }
    /***
     * 请求方法使用了不支持的请求协议
     * @author 徐恩源
     * @date 2019-12-30 10:08:39
     * @param e
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public ResponseData handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("请求协议错误：{}", e.getMessage());
        return ResponseData.error("请求方法不支持" + e.getMethod() + "协议");
    }


    /**
     * 统一处理请求参数校验(实体对象传参)
     *
     * @param e BindException
     * @return XyrlResponse
     */
    @ExceptionHandler(BindException.class)
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseData validExceptionHandler(BindException e) {
        StringBuilder message = new StringBuilder();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        for (FieldError error : fieldErrors) {
            message.append(error.getField()).append(error.getDefaultMessage()).append(StringPool.COMMA);
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        return ResponseData.error(message.toString());
    }

    /**
     * 统一处理请求参数校验(普通传参)
     *
     * @param e ConstraintViolationException
     * @return XyrlResponse
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseData handleConstraintViolationException(ConstraintViolationException e) {
        StringBuilder message = new StringBuilder();
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> violation : violations) {
            Path path = violation.getPropertyPath();
            String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), StringPool.DOT);
            message.append(pathArr[1]).append(violation.getMessage()).append(StringPool.COMMA);
        }
        message = new StringBuilder(message.substring(0, message.length() - 1));
        return ResponseData.error(message.toString());
    }

    @ExceptionHandler(value = LimitAccessException.class)
//    @ResponseStatus(HttpStatus.TOO_MANY_REQUESTS)
    public ResponseData handleLimitAccessException(LimitAccessException e) {
        log.warn(e.getMessage());
        return ResponseData.error(e.getMessage());
    }

    @ExceptionHandler(value = {UnauthorizedException.class, UnauthenticatedException.class})
    public ResponseData handleUnauthorizedException(Exception e) {
        log.error("权限不足，{}", e.getMessage());
        return ResponseData.error("访问权限不足");
    }
}
